import Base from 'models/base';
import moment from 'moment';

import SystemUtil from 'utils/systemUtil';

class GroupBargainTimes {
  constructor(data, search) {
    this.id = SystemUtil.getId();
    let startTime = moment(data.activityStartTime).valueOf();
    this.startTime = startTime;

    let endTime = moment(data.activityEndTime).valueOf();
    this.endTime = endTime;

    this.search = search;
    this.setDateText();
    this.setType();
  }

  setDateText() {
    let timeDate = moment(this.startTime);
    let nowDate = moment(this.search.nowDate);

    let dateText;
    if (timeDate.isSame(nowDate, 'day')) {
      dateText = '今天';
    } else if (timeDate.isSame(nowDate.add(-1, 'day'), 'day')) {
      dateText = '昨天';
    } else if (timeDate.isSame(nowDate.add(1, 'day'), 'day')) {
      dateText = '明天';
    } else {
      let day = timeDate.date();
      dateText = `${day>=10?day:'0'+day}号`;
    }
    this.dateText = dateText;
  }

  setType(nowTime = null) {
    if (nowTime === null) {
      nowTime = moment();
    }
    let startTime = this.startTime;
    let endTime = this.endTime;
    let type;
    if (moment(nowTime).isBefore(startTime, 'second')) {
      type = 0;
    } else if (moment(nowTime).isAfter(endTime, 'second')) {
      type = 2;
    } else {
      type = 1;
    }
    this.type = type;
  }
}

export default class GroupBargainSearch extends Base {
  constructor(dataList) {
    super();

    this.nowDate = moment().format('YYYY-MM-DD');
    let curTimes = this.initData(dataList);
    this.curTimes = curTimes;
    this.oldCurTimes = curTimes;
  }

  initData(dataList) {
    let timesList = [];
    let curTimes = null;
    for (let i = 0; i < dataList.length; i++) {
      let data = dataList[i];
      data = new GroupBargainTimes(data, this);
      timesList.push(data);

      if (curTimes === null && [0, 1].indexOf(data.type) !== -1) {
        curTimes = data;
      }
    }

    if (curTimes === null) {
      if (timesList.length > 0) {
        curTimes = timesList[timesList.length - 1];
      }
    }
    this.timesList = timesList;
    return curTimes;
  }

  toChangeType(timesObj = null) {
    let timesList = this.timesList;
    let nowTime = moment();
    let nowDate = nowTime.format('YYYY-MM-DD');
    let flag = nowDate !== this.nowDate;
    if (flag) {
      this.nowDate = nowDate;
    }
    for (let i = 0; i < timesList.length; i++) {
      const times = timesList[i];
      if (times.type !== 2 || times !== timesObj) {
        times.setType(nowTime);
      }
      if (flag) {
        times.setDateText();
      }
    }
  }
}
